Vue.prototype.$http = axios;
//每次发送axios之前都会加上这个基础路径
axios.defaults.baseURL = "http://localhost:8080";

//======================axios的前置拦截器【拦截调用后端的请求====================//
axios.interceptors.request.use(res => {
    let token = localStorage.getItem("token");
    if (token) {
        res.headers["token"] = token;
    }
    return res;
}, error => {
    Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//

//======================axios的后置拦截器【处理后台登录拦截的结果】====================//
axios.interceptors.response.use(res => {
    //后端响应的是没有登录的信息
    if (false === res.data.success && "noLogin" === res.data.message) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        localStorage.removeItem("permissions");
        localStorage.removeItem("menus");
        //跳转到前台首页
        location.href = "/login.html"
    }else if(false === res.data.success && "timeout" === res.data.message){
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        localStorage.removeItem("permissions");
        localStorage.removeItem("menus");
        router.push({path: '/login'});
    }
    return res;
}, error => {
    Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//

//静态资源拦截 ：拦截不发送axios请求的资源
//核心思路：如果你访问的不是login.html 也不是register.html 就要判断当前用户是否登录过
let url = location.href;
let path = url.substring(url.lastIndexOf("/"));
if (path != "/login.html" && path != "/register.html" && url.indexOf("binder.html") == -1 && url.indexOf("callback.html") == -1) {
    let logininfo = localStorage.getItem("logininfo");
    if(!logininfo){
        location.href="/login.html";
    }
}

/*function parseUrlParams2Obj(url){// xxx?code=111&state=222&lll=333
    var obj = {}
    //截取？后面的数据 = 参数们
    let params =  url.substring(url.indexOf("?")+1);//code=111&state=222&lll=333
    let paramsArr = params.split("&");//[code=111,state=222,lll=333]
    for(var i = 0;i<paramsArr.length;i++){
        //每一个参数
        let param = paramsArr[i];//code=111,state=222
        let paramArr = param.split("=");
        //对象的[属性名] = 属性值
        obj[paramArr[0]]=paramArr[1];
    }
    console.log(11);
    return obj;
}*/
//将地址栏的参数转成对象
function parseUrlParams2Obj(url){
    var obj = {};
    //截取问号?后面的数据
    let params = url.substring(url.indexOf("?")+1);
    //将参数参数分割
    let paramsArr = params.split("&");
    for (var i = 0; i < paramsArr.length; i++){
        //每一个参数
        let param = paramsArr[i];
        let paramArr = param.split("=");
        //对象的属性名 = 属性值
        obj[paramArr[0]] = paramArr[1];
    }
    return obj;
}